package com.guinea.skosite.web;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessages;

import com.guinea.core.Constants;
import com.guinea.core.orm.BaseEntity;
import com.guinea.core.orm.Page;
import com.guinea.core.orm.PropertyFilter;
import com.guinea.core.utils.CommonUtils;
import com.guinea.core.utils.StringUtils;
import com.guinea.core.web.StrutsAction;
import com.guinea.skoru.entity.SkoruApply;
import com.guinea.skoru.entity.SkoruRegion;
import com.guinea.skoru.entity.SkoruResume;
import com.guinea.skoru.entity.SkoruTown;
import com.guinea.skoru.form.SkoruApplyForm;
import com.guinea.skoru.service.SkoruApplyManager;
import com.guinea.skoru.service.SkoruApplyWordManager;
import com.guinea.skoru.service.SkoruRegionManager;
import com.guinea.skoru.service.SkoruResumeManager;
import com.guinea.svw.service.CommonManager;

public class SkositeApplyAction extends StrutsAction {
	private SkoruResumeManager skoruResumeManager;

	private SkoruApplyManager skoruApplyManager;
	
	private SkoruApplyWordManager skoruApplyWordManager;
	
	private SkoruRegionManager skoruRegionManager;

	private CommonManager commonManager;
	public SkoruApplyWordManager getSkoruApplyWordManager() {
		return skoruApplyWordManager;
	}

	public void setSkoruApplyWordManager(SkoruApplyWordManager skoruApplyWordManager) {
		this.skoruApplyWordManager = skoruApplyWordManager;
	}

	public SkoruApplyManager getSkoruApplyManager() {
		return skoruApplyManager;
	}

	public void setSkoruApplyManager(SkoruApplyManager skoruApplyManager) {
		this.skoruApplyManager = skoruApplyManager;
	}
	
	public SkoruRegionManager getSkoruRegionManager() {
		return skoruRegionManager;
	}

	public void setSkoruRegionManager(SkoruRegionManager skoruRegionManager) {
		this.skoruRegionManager = skoruRegionManager;
	}

	public SkoruResumeManager getSkoruResumeManager() {
		return skoruResumeManager;
	}

	public void setSkoruResumeManager(SkoruResumeManager skoruResumeManager) {
		this.skoruResumeManager = skoruResumeManager;
	}

	public CommonManager getCommonManager() {
		return commonManager;
	}

	public void setCommonManager(CommonManager commonManager) {
		this.commonManager = commonManager;
	}

	/**
	 * url参数未定义method时的默认Action函数. 默认为index Action.
	 */
	public ActionForward unspecified(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		return list(mapping, form, request, response);
	}

	/**
	 * url参数未定义method时的默认Action函数. 默认为index Action.
	 */
	public ActionForward declare(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		return mapping.findForward("declare");
	}
	
	/**
	 * url参数未定义method时的默认Action函数. 默认为index Action.
	 */
	public ActionForward download(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		String idString = request.getParameter("id");
		String regionIdString = request.getParameter("regionId");
		Long id = null;
		Long regionId = null;
		if(!StringUtils.isBlank(idString)) id=new Long(idString);
		if(!StringUtils.isBlank(regionIdString)) regionId=new Long(regionIdString);
		String fileName = "skoda_apply.doc";
		try {
			fileName = new String("斯柯达特许销售商入网申请书.doc".getBytes("gb2312"),"ISO-8859-1");
		} catch (UnsupportedEncodingException e1) {
			log.error("",e1);
		}
		response.setContentType("application/vnd.ms-word;charset=UTF-8");
		response.setHeader("Content-Disposition", "attachment; filename=\""+fileName+"\";");
		try {
			getSkoruApplyWordManager().writeWord(id,regionId,response.getWriter());
		} catch (UnsupportedEncodingException e) {
			log.error("",e);
		} catch (IOException e) {
			log.error("",e);
		}
		
		return null;
	}
	
	/**
	 * 列出所有对象的Action函数.
	 */
	public ActionForward list(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		List filters = PropertyFilter.buildFromHttpRequest(request);
		Page page = PropertyFilter.buildPageFromHttpRequest(request,"page");
		//设置默认排序方式
		if (!page.isOrderBySetted()) {
			page.setOrderBy("id");
			page.setOrder(Page.ASC);
		}
		//设置默认查询条件
		PropertyFilter filter = new PropertyFilter(Constants.FILTER_NAME, Constants.STATUS_VALID);
		filters.add(filter);
		page = getSkoruApplyManager().getApplications(page, filters);
		request.setAttribute("page", page);
		return mapping.findForward("list");
		
	}
	
	/**
	 * 显示修改对象Form的Action函数.
	 */
	public ActionForward edit(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		// 防止重复提交的token
		saveToken(request);
		
		String idString = request.getParameter("id");
		String regionIdString = request.getParameter("regionId");
		Long id = null;
		Long regionId = null;
		SkoruApplyForm applyForm = (SkoruApplyForm)form; 
		if(StringUtils.isBlank(idString) && StringUtils.isBlank(regionIdString)){
			//全部新增,带出最新一份提交申请的信息
			List as = getSkoruApplyManager().getLatestApply();
			if(as != null && as.size()>0){
				SkoruApply a = (SkoruApply)as.get(0);
				bindForm(applyForm,a);
				List resumeList = getSkoruApplyManager().getResumesByApplyId(a.getId());
				bindFormResumes(applyForm,resumeList);
			}
			//清空ID
			applyForm.setId(null);
		}else if(StringUtils.isBlank(regionIdString)){
			//申请修改，场地新增
			id = new Long(idString);
			SkoruApply apply = getSkoruApplyManager().getSkoruApply(id);
			if(apply == null){
				saveError(request, "entity.missing");
				return list(mapping, applyForm, request, response);
			}else{
				List resumeList = getSkoruApplyManager().getResumesByApplyId(id);
				//验证三条履历
				if(resumeList == null || resumeList.size() != 3){
					saveDirectlyError(request, "履历不匹配");
					return list(mapping, form, request, response);
				}
				bindForm(applyForm,apply);
				bindFormResumes(applyForm,resumeList);
//				List shareholdersList = getSkoruApplyManager().getShareholdersByApplyId(id);
			}
		}else{
			//申请修改，场地修改
			regionId = new Long(regionIdString);
			SkoruRegion region = getSkoruRegionManager().getSkoruRegion(regionId);
			SkoruApply apply = null;
			if(region != null) apply = getSkoruApplyManager().getSkoruApply(region.getApplyId());
			id = apply.getId();
			if(apply == null || region == null){
				saveError(request, "entity.missing");
				return list(mapping, form, request, response);
			}else{
				List resumeList = getSkoruApplyManager().getResumesByApplyId(id);
				// 验证三条履历
				if(resumeList == null || resumeList.size() != 3){
					saveDirectlyError(request, "履历不匹配");
					return list(mapping, applyForm, request, response);
				}
				bindForm(applyForm,apply);
				bindFormResumes(applyForm,resumeList);
				bindForm(applyForm,region);
				//重设applyId
				applyForm.setId(id);
				applyForm.setRegionId(region.getId());
//				List shareholdersList = getSkoruApplyManager().getShareholdersByApplyId(id);
			}
		}
		
		return mapping.findForward("edit");
	}
	
	/**
	 * 保存对象的Action函数.
	 */
	public ActionForward save(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		//验证TOKEN，防止重复提交
		if(!validateToken(request)) return list(mapping, form, request, response);
		
		String idString = request.getParameter("id");
		Long id = null;
		if(!StringUtils.isBlank(idString)){
			id = new Long(idString);
		}
		SkoruApply apply = null;
		SkoruResume resume1 = null;
		SkoruResume resume2 = null;
		SkoruResume resume3 = null;
		//是否新建申请
		boolean isNewApply = false;
		if(id == null) isNewApply = true;

		if(!isNewApply){
			apply = getSkoruApplyManager().getSkoruApply(id);
			List resumeList = getSkoruApplyManager().getResumesByApplyId(id);
			// 验证三条履历
			if(resumeList == null || resumeList.size() != 3){
				saveDirectlyError(request, "履历不匹配");
				return list(mapping, form, request, response);
			}else{
				for (Iterator iter = resumeList.iterator(); iter.hasNext();) {
					SkoruResume resume = (SkoruResume) iter.next();
					if(resume.getTypeCode()!= null && resume.getTypeCode().equals("1")){
						resume1 = resume;
					}else if(resume.getTypeCode()!= null && resume.getTypeCode().equals("2")){
						resume2 = resume;
					}else if(resume.getTypeCode()!= null && resume.getTypeCode().equals("3")){
						resume3 = resume;
					}
				}
			}
		}else{
			apply = new SkoruApply();
			resume1 = new SkoruResume();
			resume2 = new SkoruResume();
			resume3 = new SkoruResume();
		}
		//save操作前的验证
		ActionForward errorForward = validateBeforeSave(apply,mapping, form, request, response);
		if(errorForward != null) return errorForward;
		
		String flag = request.getParameter("flag");
		if( flag == null) flag = "save";
		
		SkoruApplyForm applyForm = (SkoruApplyForm)form; 
		// 将lazyform内容绑定到object
		bindEntity(applyForm, apply);
		// 为保存操作添加创建人更新人等信息
		BaseEntity baseEntity = addSaveData(apply,isNewApply);
		
//		applyForm.setSubmitDate(new Date());
		if("submit".equals(flag)){
			apply.setIsSubmitted("1");
			apply.setStep(new Long(1));
			//流水号
			apply.setSerial(getCommonManager().getSerial(applyForm.getProvinceId()));
		}
		getSkoruApplyManager().save(baseEntity);
		
		id = apply.getId();
		//保存履历
		bindEntityResumes(applyForm, resume1, resume2, resume3);
		resume1.setApplyId(id);
		baseEntity = addSaveData(resume1,isNewApply);
		getSkoruResumeManager().save(baseEntity);
		
		baseEntity = addSaveData(resume2,isNewApply);
		resume2.setApplyId(id);
		getSkoruResumeManager().save(baseEntity);
		
		baseEntity = addSaveData(resume3,isNewApply);
		resume3.setApplyId(id);
		getSkoruResumeManager().save(baseEntity);
		
		//保存场地
		String regionIdString = request.getParameter("regionId");
		Long regionId = null;
		if(!StringUtils.isBlank(regionIdString)){
			regionId = new Long(regionIdString);
		}
		SkoruRegion region = null;
		if(regionId != null) region = getSkoruRegionManager().getSkoruRegion(regionId);
		else region = new SkoruRegion();
		bindEntity(applyForm,region);
		region.setId(applyForm.getRegionId());
		// 为保存操作添加创建人更新人等信息
		baseEntity = addSaveData(region,(regionId == null));
		//场地必须选择省市
		if(!StringUtils.isBlank(applyForm.getProvinceId()) 
				&& !StringUtils.isBlank(applyForm.getCityId())){
			region.setApplyId(id);
			//该场地是否在计划内
			SkoruTown matchedTown = getSkoruRegionManager().getMatchedTown(region.getProvinceId(),region.getCityId(),region.getDistrictId());
			if(matchedTown != null){
				region.setIsExpected("1");
				region.setTownId(matchedTown.getId());
			}
			getSkoruRegionManager().save(region);
		}

		saveMessage(request, "entity.saved");
		//填写更多
		if(flag.equals("more"))
			return mapping.findForward("more");
		if(flag.equals("save") || flag.equals("next") || flag.equals("image")){
			String url = "/skositedo/apply.do?method=edit&id="+id;
			if(region.getId() != null) url += "&regionId=" + region.getId().longValue();
			return new ActionForward(url,true);
		}
		return mapping.findForward(SUCCESS);
	}
	
	/**
	 * 验证TOKEN
	 * @param request
	 * @return
	 */
	protected boolean validateToken(HttpServletRequest request){
		if (isCancelled(request))
			return false;
		if (!isTokenValid(request)) {
			saveDirectlyError(request, "重复提交");
			return false;
		}
		resetToken(request);
		return true;
	}
	/**
	 * save操作前的验证
	 * @param object
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 */
	protected ActionForward validateBeforeSave(Object object,ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response){
		String flag = request.getParameter("flag");
		if( flag == null) flag = "save";
		
		//上传文件大小
		SkoruApplyForm applyForm = (SkoruApplyForm) form;
		
//		if(flag.equals("save") || flag.equals("next") || flag.equals("image")){
//			//保存操作，仅做基本验证
//			if(StringUtils.isBlank(applyForm.getCorp()) || applyForm.getCorp().length()>200){
//				saveDirectlyError(request,"请填写公司名称，不超过200字");
//				//返回第一步
//				applyForm.setStep(new Long(1));
//				return edit(mapping, applyForm, request, response);
//			}
//
//		}
		if(flag.equals("image")|| flag.equals("submit")|| flag.equals("more")){
			//拟建场地
			if(StringUtils.isBlank(applyForm.getProvinceId()) 
					||StringUtils.isBlank(applyForm.getCityId())){
				saveDirectlyError(request,"请选择投资区域的省市");
				// 返回第6步
				applyForm.setStep(new Long(6));
				return null;
			}
		}
			//提交，验证表单
			ActionMessages errors = form.validate(mapping, request);
			if (!errors.isEmpty()) {
				saveErrors(request, errors);
				return edit(mapping, form, request, response);
			}
		if (object == null) {
			saveError(request, "entity.missing");
			return list(mapping, form, request, response);
		}
		return null;
	}

	private void bindFormResumes(ActionForm form,List resumeList){
		if(form != null){
			SkoruApplyForm applyForm = (SkoruApplyForm)form;
			if(resumeList != null)
				for (Iterator iter = resumeList.iterator(); iter.hasNext();) {
					SkoruResume resume = (SkoruResume) iter.next();
					if(resume != null && resume.getTypeCode() != null){
						if(resume.getTypeCode().equals("1")){
							//董事长
							applyForm.setResumeId1(resume.getId());
							applyForm.setBirthDay1(resume.getBirthDay());
							applyForm.setBirthMonth1(resume.getBirthMonth());
							applyForm.setBirthYear1(resume.getBirthYear());
							applyForm.setCellphone1(resume.getCellphone());
							applyForm.setEmail1(resume.getEmail());
							applyForm.setGender1(resume.getGender());
							applyForm.setNote1(resume.getNote());
							applyForm.setOwner1(resume.getOwner());
							applyForm.setSchoolAge1(resume.getSchoolAge());
						}else if(resume.getTypeCode().equals("2")){
							//总经理
							applyForm.setResumeId2(resume.getId());
							applyForm.setBirthDay2(resume.getBirthDay());
							applyForm.setBirthMonth2(resume.getBirthMonth());
							applyForm.setBirthYear2(resume.getBirthYear());
							applyForm.setCellphone2(resume.getCellphone());
							applyForm.setEmail2(resume.getEmail());
							applyForm.setGender2(resume.getGender());
							applyForm.setNote2(resume.getNote());
							applyForm.setOwner2(resume.getOwner());
							applyForm.setSchoolAge2(resume.getSchoolAge());
						}else if(resume.getTypeCode().equals("3")){
							//意向经理
							applyForm.setResumeId3(resume.getId());
							applyForm.setBirthDay3(resume.getBirthDay());
							applyForm.setBirthMonth3(resume.getBirthMonth());
							applyForm.setBirthYear3(resume.getBirthYear());
							applyForm.setCellphone3(resume.getCellphone());
							applyForm.setEmail3(resume.getEmail());
							applyForm.setGender3(resume.getGender());
							applyForm.setNote3(resume.getNote());
							applyForm.setOwner3(resume.getOwner());
							applyForm.setSchoolAge3(resume.getSchoolAge());
						}
					}
				}
		}
	}
	/**
	 * 将FormBean中的内容通过BeanUtils的copyProperties()绑定到Object中. 因为BeanUtils中两个参数的顺序很容易搞错，因此封装此函数.
	 */
	protected void bindEntityResumes(SkoruApplyForm form, SkoruResume resume1, SkoruResume resume2, SkoruResume resume3) {
		if (form != null) {
			if(resume1 != null){
				//董事长履历
				resume1.setId(form.getResumeId1());
				resume1.setTypeCode("1");
				resume1.setBirthDay(form.getBirthDay1());
				resume1.setBirthMonth(form.getBirthMonth1());
				resume1.setBirthYear(form.getBirthYear1());
				resume1.setCellphone(form.getCellphone1());
				resume1.setEmail(form.getEmail1());
				resume1.setGender(form.getGender1());
				resume1.setNote(form.getNote1());
				resume1.setOwner(form.getOwner1());
				resume1.setSchoolAge(form.getSchoolAge1());
			}
			
			if(resume2 != null){
				//总经理履历
				resume2.setId(form.getResumeId2());
				resume2.setTypeCode("2");
				resume2.setBirthDay(form.getBirthDay2());
				resume2.setBirthMonth(form.getBirthMonth2());
				resume2.setBirthYear(form.getBirthYear2());
				resume2.setCellphone(form.getCellphone2());
				resume2.setEmail(form.getEmail2());
				resume2.setGender(form.getGender2());
				resume2.setNote(form.getNote2());
				resume2.setOwner(form.getOwner2());
				resume2.setSchoolAge(form.getSchoolAge2());
			}
			
			if(resume3 != null){
				//意向经理履历
				resume3.setId(form.getResumeId3());
				resume3.setTypeCode("3");
				resume3.setBirthDay(form.getBirthDay3());
				resume3.setBirthMonth(form.getBirthMonth3());
				resume3.setBirthYear(form.getBirthYear3());
				resume3.setCellphone(form.getCellphone3());
				resume3.setEmail(form.getEmail3());
				resume3.setGender(form.getGender3());
				resume3.setNote(form.getNote3());
				resume3.setOwner(form.getOwner3());
				resume3.setSchoolAge(form.getSchoolAge3());

			}
		}
	}
	
	/**
	 * 为保存操作添加创建人更新人等信息，保存操作专用
	 * @param isNewEntity 是否创建新对象
	 * @param object
	 * @return
	 */
	protected BaseEntity addSaveData(Object object,boolean isNewEntity){
		//保存创建人更新人
		BaseEntity baseEntity = (BaseEntity) object;
		Long userId = CommonUtils.getCurrentUserId();
		if(userId == null) userId = new Long(0);
		//新增
		if(isNewEntity){
			baseEntity.setStatus(Constants.STATUS_VALID);
			baseEntity.setCreator(userId);
			baseEntity.setCreated(new Date());
		}else {//修改
			baseEntity.setModificator(userId);
			baseEntity.setModified(new Date());
		}
		return baseEntity;
	}
}
